package web

import (
	"basic-go/syntax/webook/internal/service"
	"basic-go/syntax/webook/internal/service/oauth2/wechat"
	"github.com/gin-gonic/gin"
	uuid "github.com/lithammer/shortuuid/v4"
	"net/http"
)

type Oauth2WechatHandler struct {
	wcsvc   wechat.Oauth2WechatService
	usersvc service.UserService
	JWTHandler
}

func NewOauth2WechatHandler(svc wechat.Oauth2WechatService, svcuser service.UserService) *Oauth2WechatHandler {
	return &Oauth2WechatHandler{
		wcsvc:   svc,
		usersvc: svcuser,
	}
}

func (h *Oauth2WechatHandler) RegisterRoutes(server *gin.Engine) {
	g := server.Group("/oauth2/wechat")
	g.GET("/authurl", h.Oauth2Url)
	g.Any("/callback", h.CallBack)
}

func (h *Oauth2WechatHandler) Oauth2Url(ctx *gin.Context) {
	state := uuid.New()
	oauthUrl, err := h.wcsvc.AuthUrl(ctx, state)
	if err != nil {
		ctx.JSON(http.StatusOK, Result{
			Code: 5,
			Msg:  "构造扫码登录URL失败",
		})
	}
	ctx.JSON(http.StatusOK, Result{
		Data: oauthUrl,
	})
}

func (h *Oauth2WechatHandler) CallBack(ctx *gin.Context) {
	// 用户授权后，微信会重定向到redirect_uri的网址上，并且带上code和state参数
	// redirect_uri?code=CODE&state=STATE
	// 从url中获取 ？code=xxx 的值
	code := ctx.Query("code")
	wcInfo, err := h.wcsvc.VerifyCode(ctx, code)
	if err != nil {
		ctx.JSON(http.StatusOK, Result{Code: 5, Msg: "系统错误"})
		return
	}
	user, err := h.usersvc.FindOrCreateByWechat(ctx, wcInfo)
	if err != nil {
		ctx.JSON(http.StatusOK, Result{
			Code: 5,
			Msg:  "系统错误",
		})
		return
	}

	//todo 在这里设置 token 或session
	//_ = user.Id
	err = h.SetJWTToken(ctx, user.Id)
	if err != nil {
		ctx.JSON(http.StatusOK, Result{
			Code: 5,
			Msg:  "系统错误",
		})
		return
	}

	ctx.JSON(http.StatusOK, Result{
		Msg: "OK",
	})
}
